package com.joint.web.action.finance;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.finance.FinanceYear;
import com.joint.core.service.FinanceYearService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/9.
 */
@ParentPackage("finance")
public class AjaxFinanceyearAction extends BaseFlowAction {
    @Resource
    private FinanceYearService financeYearService;
    @Resource
    private DepartmentService departmentService;
    private FinanceYear financeYear;
    private Users loginUser;
    private String viewtype;
    private int ifCentralStaff;
    private int numStatus;
    private String fileId;
    private String fileIds;
    private int year;
    private String yearId;
    private String departmentId;

    public String execute(){
        return "financeyear";
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state", BaseEnum.StateEnum.Enable);
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=financeYearService.findByPagerAndLimit(true, "financeyear", pager, params);
        List<FinanceYear> fyList;
        if (pager.getTotalCount() > 0){
            fyList = (List<FinanceYear>) pager.getList();
        }else{
            fyList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(FinanceYear f:fyList){
            String state=f.getProcessState().name();
            rMap = new HashMap<String,Object>();
            rMap.put("id", f.getId());
            rMap.put("year", f.getYear());
            rMap.put("department", f.getDepartment().getName());
            rMap.put("state", f.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String input(){
        year= Calendar.getInstance().get(Calendar.YEAR);
        if(StringUtils.isNotEmpty(keyId)){
            fileId="";
            financeYear=financeYearService.get(keyId);
            if(financeYear.getFile()!=null&&financeYear.getFile().size()>0){
                for(FileManage f:financeYear.getFile()){
                    fileId+=f.getId()+",";
                }
            }
        }
        return "input";
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            financeYear=financeYearService.get(keyId);
            fileId="";
            if(financeYear.getFile()!=null&&financeYear.getFile().size()>0){
                for(FileManage f:financeYear.getFile()){
                    fileId+=f.getId()+",";
                }
            }
        }
        return "read";
    }

    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                financeYearService.update(financeYear);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("initDuty", curDutyId);
                various.put("curDutyId", curDutyId);
                financeYearService.save(financeYear, "financeyear", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            financeYear=financeYearService.get(keyId);
        }else{
            financeYear=new FinanceYear();
            financeYear.setCreater(usersService.getLoginInfo());
        }
        financeYear.setYear(yearId);
        financeYear.setDepartment(departmentService.get(departmentId));
        financeYear.setCompany(usersService.getLoginInfo().getCompany());
        List<FileManage> fileList= Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileList.add(fileManageService.get(f.trim()));
            }
            financeYear.setFile(fileList);
        }
    }

    public String commit(){
        Company company = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("processState", new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished,FlowEnum.ProcessState.Running});
        params.put("year", yearId);
        List<FinanceYear> list = (List<FinanceYear>)financeYearService.findByPagerAndCompany(null, null, company, params).getList();
        if(list.size()>0){
            return ajaxHtmlCallback("400", "每年只能新建一次", "操作状态");
        }
        setData();
        ifCentralStaff=0;
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();

        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi" + duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        if(ifCentralStaff==1){
            var1.put("numStatus",3);
            var2.put("numStatus",3);
        }else{
            var1.put("numStatus",1);
            var2.put("numStatus", 1);
        }
        var2.put("curDutyId", curDutyId);
        var2.put("ifCentralStaff", ifCentralStaff);
        List<String> list1  =Lists.newArrayList();
        for(Duty duty:dutySet){
            Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
            Set<Department> deptSet=dept.getChildren();
            for(Department cdept:deptSet){
                if(cdept.getName().contains("财务科")){
                    Set<Power> powers = cdept.getPowerSet();
                    for(Power power:powers){
                        if(power.getPost().getName().equals("科长")){
                            List<Users> usersList=dutyService.getPersons(cdept,power.getPost());
                            for(Users user:usersList){
                                list1.add(user.getId().trim());
                            }
                        }
                    }
                }

            }
        }
        var1.put("approver", list1);
        var2.put("approver", list1);
        List<String> list2=Lists.newArrayList();
        for(Duty duty:dutySet){
            Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
            Set<Power> powers = dept.getPowerSet();
            for(Power power:powers){
                if(power.getPost().getName().equals("总经理")){
                    List<Users> usersList=dutyService.getPersons(dept,power.getPost());
                    for(Users user:usersList){
                        list2.add(user.getId().trim());
                    }
                }
            }
        }
        var1.put("approver1", list2);
        var2.put("approver1", list2);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                financeYearService.approve(financeYear, FlowEnum.ProcessState.Running, var2, curDutyId, comment);
            } else {
                keyId = financeYearService.commit(financeYear, "financeyear", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve1(){
        ifCentralStaff=0;
        financeYear = financeYearService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi"+duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                financeYearService.approve(financeYear, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        financeYear = financeYearService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 3);
        //  var2.put("curDutyId", curDutyId);
        try {
            financeYearService.approve(financeYear, FlowEnum.ProcessState.Running, var2, curDutyId,comment);

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        financeYear = financeYearService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        //  var2.put("curDutyId", curDutyId);
        try {
            financeYearService.approve(financeYear, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve4() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        financeYear = financeYearService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 5);
        //  var2.put("curDutyId", curDutyId);
        try {
            financeYearService.approve(financeYear, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            financeYear = financeYearService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("financeyear");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:" + numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            financeYearService.reject(financeYear, key, numStatus, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            financeYear = financeYearService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("financeyear");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            financeYearService.deny(financeYear, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }



    public FinanceYear getFinanceYear() {
        return financeYear;
    }

    public void setFinanceYear(FinanceYear financeYear) {
        this.financeYear = financeYear;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getYearId() {
        return yearId;
    }

    public void setYearId(String yearId) {
        this.yearId = yearId;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }
}
